<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowDown, Search } from '@element-plus/icons-vue'
import {
  exportExcelApi,
  exportResumeAttachedByAttachedIdApi,
  getResumesLimitApi,
  postChangeResumeStatusByResumeIdApi
} from '@/apis/resume'
import { getStationsLimitByManagerNameApi } from '@/apis/station'

const tableLoading = ref(false)
const exportExcelLoading = ref(false)
// 分页参数
const pageparm = ref({
  pageNum: 1,
  pageSize: 10,
  total: 10
})
// 请求参数
const resumeRequstParam = reactive({
  data: {
    stationId: '',
    name: '',
    status: ''
  }
})
const resumes = ref([])
const stations = ref([])
// 共享值
const stationIdConvertCount = ref(0)
const resumeStatus = ref(['未沟通', '已沟通', '有意向', '已加入', '已拒绝'])
const resumeStatusSelector = ref(' ')

// 获取简历
const getResume = state => {
  if (state != undefined) {
    resumeRequstParam.data.status = state
  }
  tableLoading.value = true
  getResumesLimitApi(
      resumeRequstParam.data.name,
      resumeRequstParam.data.stationId,
      resumeRequstParam.data.status,
      pageparm.value.pageNum,
      pageparm.value.pageSize
  )
      .then(({data}) => {
        resumes.value = data.dataList
        pageparm.value.total = data.total
        stationIdConvertName()
      })
      .finally(() => {
        tableLoading.value = false
      })
}

// 岗位ID转岗位名称
const stationIdConvertName = () => {
  if (++stationIdConvertCount.value >= 2) {
    for (let i = 0; i < resumes.value.length; ++i) {
      for (let j = 0; j < stations.value.length; ++j) {
        if (resumes.value[i].stationId === stations.value[j].id) {
          resumes.value[i].stationId = stations.value[j].stationName
        }
      }
    }
  }
}

// 下载简历附件
const getResumeFile = resume => {
  exportResumeAttachedByAttachedIdApi(resume.attachedId).then(res => {
    let blob = new Blob([res]) // 将返回的数据通过Blob的构造方法，创建Blob对象
    if ('msSaveOrOpenBlob' in navigator) {
      window.navigator.msSaveOrOpenBlob(blob, resume.name + '.pdf') // 针对浏览器
    } else {
      const elink = document.createElement('a') // 创建a标签
      elink.download = resume.name + '.pdf'
      elink.style.display = 'none'
      // 创建一个指向blob的url，这里就是点击可以下载文件的根结
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) //移除链接
      document.body.removeChild(elink) //移除a标签
    }
  })
}

// 获取岗位
const getStations = () => {
  getStationsLimitByManagerNameApi('%', pageparm.value.pageNum, 100).then(({data}) => {
    stations.value = data.dataList
    stationIdConvertName()
  })
}

// 修改当前页码
const handleChangePage = pageNum => {
  pageparm.value.pageNum = pageNum
  getResume()
}

// 改变当前简历状态
const handleDropdownChangeStatus = (index, row) => {
  postChangeResumeStatusByResumeIdApi(row.id, index).then(() => {
    getResume(row.status)
    ElMessage({
      type: 'success',
      dangerouslyUseHTMLString: true,
      message: `<br>${ row.name }的简历状态已修改为 <strong><i>${ resumeStatus.value[index - 1] }</i></strong>`
    })
  })
}

// 导出提示
const openExportDialog = () => {
  exportExcelLoading.value = true
  ElMessage({type: 'warning', message: '表单导出中，请勿重复点击'})
  setTimeout(() => {
    exportExcelApi()
        .then(res => {
          let blob = new Blob([res]) // 将返回的数据通过Blob的构造方法，创建Blob对象

          if ('msSaveOrOpenBlob' in navigator) {
            window.navigator.msSaveOrOpenBlob(blob) // 针对浏览器
          } else {
            const elink = document.createElement('a') // 创建a标签
            elink.style.display = 'none'
            const date = new Date()
            elink.download = `玉环-投递记录-导出时间：${ date.getFullYear() }-${ (date.getMonth() + 1)
                .toString()
                .padStart(2, '0') }-${ date.getDate() }+${ date
                .getHours()
                .toString()
                .padStart(2, '0') }_${ date.getMinutes() }_${ date.getSeconds() }.xlsx`
            // 创建一个指向blob的url，这里就是点击可以下载文件的根结
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) //移除链接
            document.body.removeChild(elink) //移除a标签
            ElMessage({message: '导出成功！', type: 'success'})
          }
        })
        .finally(() => (exportExcelLoading.value = false))
  }, 1000)
}

onMounted(() => {
  getResume()
  getStations()
})
</script>

<template>
  <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 24px">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>简历管理</el-breadcrumb-item>
  </el-breadcrumb>
  <el-form :inline="true" class="user-search" style="display: flex; justify-content: space-between">
    <div>
      <el-form-item label="岗位：">
        <el-select v-model="resumeRequstParam.data.stationId" placeholder="请选择负责人" style="width: 200px">
          <el-option key="" label="全部岗位" value=""></el-option>
          <el-option v-for="item in stations" :key="item.id" :label="item.stationName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="投递人姓名：">
        <el-input v-model="resumeRequstParam.data.name" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getResume(resumeRequstParam.data.status)">搜索</el-button>
      </el-form-item>
    </div>
    <el-form-item>
      <el-button type="primary" @click="openExportDialog" :loading="exportExcelLoading">
        <img
            src="../../assets/imgs/export.png"
            style="width: 12px; height: 12px"
            v-if="!exportExcelLoading"
            :disabled="exportExcelLoading"
        />
        <span v-if="!exportExcelLoading">&ensp;导出</span>
        <span v-else>&ensp;导出中</span>
      </el-button>
    </el-form-item>
  </el-form>
  <el-radio-group v-model="resumeStatusSelector" @change="getResume" style="margin-bottom: 24px">
    <el-radio-button label=" ">全部</el-radio-button>
    <el-radio-button v-for="(status, index) in resumeStatus" :key="index" :label="index + 1">
      {{ status }}
    </el-radio-button>
  </el-radio-group>
  <!--列表-->
  <el-table :data="resumes" highlight-current-row v-loading="tableLoading" stripe style="width: 100%" height="76%">
    <el-table-column align="center" type="selection" width="60"></el-table-column>
    <el-table-column sortable prop="name" label="姓名" width="100"></el-table-column>
    <el-table-column sortable prop="stationId" label="岗位" width="120"></el-table-column>
    <el-table-column sortable prop="school" label="学校" width="200"></el-table-column>
    <el-table-column sortable prop="academy" label="学院" width="200"></el-table-column>
    <el-table-column sortable prop="studentId" label="学号" width="200"></el-table-column>
    <el-table-column sortable prop="grade" label="年级" width="100"></el-table-column>
    <el-table-column sortable prop="nationality" label="民族" width="100"></el-table-column>
    <el-table-column sortable prop="political" label="政治面貌" width="100"></el-table-column>
    <el-table-column sortable prop="age" label="年龄" width="100"></el-table-column>
    <el-table-column sortable prop="sex" label="性别" width="100"></el-table-column>
    <el-table-column sortable prop="qq" label="qq" width="100"></el-table-column>
    <el-table-column sortable prop="email" label="邮箱" width="170"></el-table-column>
    <el-table-column sortable prop="telephone" label="电话" width="200"></el-table-column>
    <el-table-column sortable prop="feedBack" label="投递来源" width="100"></el-table-column>
    <el-table-column sortable prop="award" label="获取荣誉" width="300"></el-table-column>
    <el-table-column sortable prop="activities" label="参加活动" width="300"></el-table-column>
    <el-table-column sortable prop="deliveryTime" label="投递时间" width="160"></el-table-column>
    <el-table-column label="操作" min-width="200" fixed="right">
      <template #default="scope">
        <el-button type="primary" @click="getResumeFile(scope.row)" :disabled="scope.row.attachedId == 58">
          下载
        </el-button>
        &ensp;
        <el-dropdown @command="handleDropdownChangeStatus($event, scope.row)">
          <el-button type="primary">
            {{ resumeStatus[scope.row.status - 1] }}
            <el-icon class="el-icon-arrow-down el-icon--right">
              <arrow-down />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(status, index) in resumeStatus" :key="status" :command="index + 1">
                {{ status }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      background
      @current-change="handleChangePage"
      :page-size="pageparm.pageSize"
      layout="total, prev, pager, next"
      :total="pageparm.total"
  >
  </el-pagination>
</template>

<style lang="less" scoped>
.user-search {
  margin-top: 20px;
}

:deep(.el-table__inner-wrapper) {
  height: 100% !important;
}
</style>
